package com.mx.controller;

import com.mx.pojo.Article;
import com.mx.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

@Controller
public class TestController {

    @Autowired
    ArticleService articleService;

    @RequestMapping("/test")
    public String test(Model model){
        List<Article> all = articleService.findAll();
        model.addAttribute("content",all.get(0).getContent());
        return "test";
    }


    @RequestMapping("/upload")
    @ResponseBody
    public String upload(String username,String password,@RequestParam("file") MultipartFile pic){
        System.out.println("username:"+username);
        System.out.println("password:"+password);
        String downloadPath;
        if(pic.isEmpty()){
            System.err.println("上传的图片为空");
        }
        else{
            // ResourceUtils.getURL("classpath:") 是获取当前文件的resources路径
            try {
                // 获取文件的原始名称
                String oldFileName = pic.getOriginalFilename();
                String realPath = ResourceUtils.getURL("classpath:").getPath() + "static/files";
                // 处理文件上传
                realPath=realPath.substring(1);
                File file = new File(realPath);
                System.out.println(file.exists());
                if(!file.exists())
                    file.mkdir();
                System.out.println(realPath);
                pic.transferTo(new File(realPath,oldFileName));
                downloadPath="/files/"+oldFileName;
                System.out.println("downloadPath:/files/"+oldFileName);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "test";
    }
}
